package com.example.qundui.learndemo;

import android.Manifest;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_ASK__INTENT =300 ;
    private DownloadManager downloadManager;
    private String PATH;
    private long pid;
   private ImageView iv;
    private DownLoadReceiver d;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv= (ImageView) findViewById(R.id.iv);
        initdownloadSystem();
    }
    /**
     * 初始化系统下载框架
     */
    private void initdownloadSystem() {
        downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);

    }
    public void download(View view){
        checkPermission();
       // downappImp();
    }

    private void checkPermission() {
        if (Build.VERSION.SDK_INT>=23){
            int checkIntentPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET);
            if(checkIntentPermission != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.INTERNET},REQUEST_CODE_ASK__INTENT);
                return;
            }else{

                downappImp();
            }
        } else {
            downappImp();
        }

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK__INTENT:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    downappImp();
                } else {
                    // Permission Denied
                    Toast.makeText(MainActivity.this, "INTENT Denied", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
    private void downappImp() {
       // http://api.nohttp.net/download/1.apk
        PATH="http://api.nohttp.net/download/1.apk";
        Uri uri=Uri.parse(PATH);
        DownloadManager.Request request=new DownloadManager.Request(uri);
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);//允许在wifi下下载
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setMimeType("application/vnd.android.package-archive");
        request.setTitle("下载apk...");
        request.setDestinationInExternalFilesDir(this,
                Environment.DIRECTORY_DOWNLOADS, "gsc.apk");//制定下载后保存的路径
        pid = downloadManager.enqueue(request);//根据这个值取消
        regidit();
        selectProcess(pid);
        //photo2();


    }

    private void photo2() {
        Picasso.with(this).load(PATH).into(iv);
    }


    private void regidit() {
         d=new DownLoadReceiver();
        IntentFilter filter=new IntentFilter();
        filter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
        filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        registerReceiver(d,filter);
    }

    private void selectProcess(long pid) {
        Log.i("gsc", "selectProcess: pid="+pid);
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(pid);
        Cursor cursor = downloadManager.query(query);
        if (cursor != null) {
            while (cursor.moveToNext()) {

                String bytesDownload = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                String descrition = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_DESCRIPTION));
                String id = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_ID));
                String localUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                String mimeType = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
                String title = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE));
                String status = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                String totalSize = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                Log.i("MainActivity", "bytesDownload:" + bytesDownload);
                Log.i("MainActivity", "descrition:" + descrition);
                Log.i("MainActivity", "id:" + id);
                Log.i("MainActivity", "localUri:" + localUri);
                Log.i("MainActivity", "mimeType:" + mimeType);
                Log.i("MainActivity", "title:" + title);
                Log.i("MainActivity", "status:" + status);
                Log.i("MainActivity", "totalSize:" + totalSize);

            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(d);
    }

    class DownLoadReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {

                Uri uri = downloadManager.getUriForDownloadedFile(pid);
                iv.setImageURI(uri);

            } else if (intent.getAction().equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {

                Toast.makeText(context, "Clicked", Toast.LENGTH_SHORT).show();

            }
        }
    }
}
